package cn.rui.utils;

/**
 * 生成图片验证码
 */

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

//@WebServlet("/checkCode")
@RestController
@RequestMapping("checkCode")
public class CheckCodeServlet extends HttpServlet {

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("code")
    public void getCode(HttpServletResponse response) throws Exception{
        int width = 100;
        int height = 40;
        //1,创建一对象，在内存中图片(验证码图片对象)
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        //2,美化图片
        //2.1 填充背景色
        Graphics g = image.getGraphics();//画笔对象
        g.setColor(Color.pink);//设置画笔颜色
        g.fillRect(0, 0, width, height);

        //2.2 画边框
        g.setColor(Color.blue);
        g.drawRect(0, 0, width - 1, height - 1);

        String str = "ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        //生成随机角标
        Random ran = new Random();

        String checkCode="";
        for (int i = 1; i <= 4; i++) {
            int index = ran.nextInt(str.length());
            //获取字符
            char ch = str.charAt(index);

            checkCode=checkCode+ch;

            //随机写验证码内容
            g.drawString(ch + "", width / 5 * i, height / 2);
        }

        redisTemplate.delete ("code");
        redisTemplate.opsForValue ().set ("code",checkCode);
        //request.getSession ().setAttribute ("checkCode",checkCode);


        //2.3 写验证码内容
       /* g.drawString("A", 20, 25);
        g.drawString("B", 40, 25);
        g.drawString("C", 60, 25);
        g.drawString("D", 80, 25);*/

        //2.4 画干扰线
        g.setColor(Color.green);

        //随机生成坐标点
        for (int i = 0; i <10 ; i++) {

            int x1 = ran.nextInt(width);
            int x2 = ran.nextInt(width);
            int y1 = ran.nextInt(height);
            int y2 = ran.nextInt(height);

            g.drawLine(x1,x2,y1,y2);
        }

        //3,将图片输出到页面展示
        ImageIO.write(image, "jpg", response.getOutputStream());
    }


    /*public String checkCode(HttpServletRequest request){
        Object checkCode = request.getSession ().getAttribute ("checkCode");

        return checkCode.toString ();
    }*/
}